/*
 * ShiroDataBaseRealm
 * V 1.0.0
 * 2013/1/7
 *
 * Copyright © 2012 中国电信股份有限公司增值业务运营中心 版权所有
 *
 * 所有文字、代码资料，版权均属中国电信股份有限公司增值业务运营中心
 * 所有，任何公司或个人未经本司协议授权，不得复制、下载、存储或公开
 * 显示。违者本公司将依法追究责任。
 */
package cn.com.yxw.webapp.common.security;

import cn.com.yxw.webapp.pojo.Admin;
import cn.com.yxw.webapp.service.AdminService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Shiro验证
 * @author liutong01
 * 
 */
@Service
public class ShiroDataBaseRealm extends AuthorizingRealm {

	@Autowired
	private AdminService adminService;

	/**
	 * 授权
	 * @param principals
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Admin admin = (Admin)principals.getPrimaryPrincipal();
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo();
		admin = adminService.findByUsername(admin.getUsername());

		return null;
	}

	/**
	 * 身份验证操作
	 *
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
		String username = usernamePasswordToken.getUsername();
		
		if (StringUtils.isBlank(username))
			throw new AccountException("用户名不能为空");

		Admin _user = adminService.selectAdminByUserName(username);
		if (_user == null)
			throw new UnknownAccountException("用户不存在");

		// 传入正确密码（因为系统使用UDB已经验证了密码，所以传入密码为空，验证时正确的密码也为空）
		return new SimpleAuthenticationInfo(_user, _user.getPassword(), ByteSource.Util.bytes(_user.getKey()), getName());
	}

	final Logger logger = LoggerFactory.getLogger(ShiroDataBaseRealm.class);
}
